package node.block.stmt;

import midcode.MidCode;
import midcode.MidcodeGenerator;
import midcode.OPType;
import node.Node;
import node.exp.Cond;

public class IfStmt implements Node {
    private Node ifStmt;
    private Node elseStmt;
    private Cond cond;
    private String label1;
    private String label2;
    private String label3;

    public IfStmt(Cond cond, Node ifStmt) {
        this.cond = cond;
        this.ifStmt = ifStmt;
        cond.setFather(this);
    }

    public void setElseStmt(Node elseStmt) {
        this.elseStmt = elseStmt;
    }

    public String getLabel1() {
        return label1;
    }

    public String getLabel2() {
        return label2;
    }

    @Override
    public Node getFather() {
        return father;
    }

    @Override
    public String genMidCode() {
        MidcodeGenerator mg = MidcodeGenerator.getInstance();
        if (cond.getLAndNum() > 1) {
            label1 = mg.genLabel();
        }
        label2 = mg.genLabel();
        cond.genMidCode();
        if (cond.getLAndNum() > 1) {
            mg.addMidcode(new MidCode(OPType.LABEL_GEN, null, null, label1));
        }
        ifStmt.genMidCode();
        if (elseStmt == null) {
            mg.addMidcode(new MidCode(OPType.LABEL_GEN, null, null, label2));
        } else {
            label3 = mg.genLabel();
            mg.addMidcode(new MidCode(OPType.GOTO, null, null, label3));
            mg.addMidcode(new MidCode(OPType.LABEL_GEN, null, null, label2));
            elseStmt.genMidCode();
            mg.addMidcode(new MidCode(OPType.LABEL_GEN, null, null, label3));
        }
        return "";
    }
}

